package main

import (
	. "RpcNasSync/config/serve"
	"RpcNasSync/logger"
	_ "RpcNasSync/logger"
	"RpcNasSync/service"
	"flag"
	"github.com/smallnest/rpcx/server"
	"github.com/smallnest/rpcx/serverplugin"
	"github.com/smallnest/rpcx/share"
	"go.uber.org/zap"
	"log"
)

var (
	servePort = flag.String("servePort", "36952", "server port")
	TransPort = flag.String("transPort", "36953", "file transfer port")
)

func main() {
	// 读取配置文件
	if err := DefaultInnerConfig.LoadConfig("rpc_sync.conf"); err != nil {
		log.Fatal(err)
	}

	if err := DefaultInnerConfig.NewInnerIp(); err != nil {
		log.Fatal(err)
	}

	logger.Init(&DefaultInnerConfig.Config)
	//flag.Parse()
	// 创建 rpcx 服务实例
	s := server.NewServer()

	whiteIpList := make(map[string]bool)
	for _, ip := range DefaultInnerConfig.Config.WhiteIpList {
		whiteIpList[ip] = true
	}

	s.Plugins.Add(&serverplugin.WhitelistPlugin{
		Whitelist:      whiteIpList,
		WhiteServeList: DefaultInnerConfig.InnerIp,
	})
	// 注册命令执行服务
	err := s.RegisterName("ServiceShell", new(service.ServiceShell), "")
	if err != nil {
		logger.LogError("Error RegisterName", zap.String("ServiceName", "ServiceShell"))
		return
	}

	// 注册文件传输服务
	//p := server.NewFileTransfer(client.SPNode.Hosts["L:SP1"]+":"+cfg.TransPort, service.SaveFileHandler, service.DownloadFileHandler, 1000)
	//a := server.NewFileTransfer("172.0.1.202"+":"+cfg.TransPort, service.SaveFileHandler, service.DownloadFileHandler, 1000)
	p := server.NewFileTransfer(":"+DefaultInnerConfig.Config.TransPort, service.SaveFileHandler, service.DownloadFileHandler, 1000)
	s.EnableFileTransfer(share.SendFileServiceName, p)

	// 启动服务监听
	logger.LogInfo("server start", zap.String("listen port", DefaultInnerConfig.Config.ServePort))
	//err = s.Serve("tcp", client.SPNode.Hosts["L:SP1"]+":"+cfg.ServePort)
	err = s.Serve("tcp", ":"+DefaultInnerConfig.Config.ServePort)
	if err != nil {
		logger.LogError("server start failed", zap.Error(err))
		log.Fatal(err)
	}

}
